package com.syh.app.basic.base;


import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.syh.app.basic.App;
import com.syh.app.basic.base.view_model.BaseMldEvent;
import com.syh.app.basic.base.view_model.BaseViewModel;
import com.trello.rxlifecycle2.android.FragmentEvent;
import com.trello.rxlifecycle2.components.support.RxFragment;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import static com.syh.app.basic.base.BaseActivity.FINISH;
import static com.syh.app.basic.base.BaseActivity.FINISH_WITH_RESULT;
import static com.syh.app.basic.base.BaseActivity.HIDE_LOADING;
import static com.syh.app.basic.base.BaseActivity.SHOW_LOADING;

/**
 * 创建者：SYH
 * 时间：2019/9/30 10:56
 * 编辑者：SYH、
 * 补充说明：
 */
public abstract class BaseFragment<VDB extends ViewDataBinding, VM extends BaseViewModel<FragmentEvent>> extends RxFragment {

    protected VDB mVDBinding;
    protected VM mViewModel;
    protected BaseActivity mActivity;
    protected boolean isFirstVisible = true;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mVDBinding = DataBindingUtil.inflate(inflater, getContentLayout(), container, false);
        mViewModel = (VM) new ViewModelProvider(getViewModelStore(), ViewModelProvider.AndroidViewModelFactory.getInstance(App.getApplication())).get(getViewModelClass());
        mVDBinding.setVariable(getViewModelId(), mViewModel);
        mViewModel.initLifecycleProvider(this);
        initBundleData();
        return mVDBinding.getRoot();
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        getLifecycle().addObserver(mViewModel);
        initView();
        initObservers();
        initData();
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        this.mActivity = (BaseActivity) activity;
    }

    @Override
    public void onDetach() {
        super.onDetach();
        this.mActivity = null;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden && !isFirstVisible) {
            visibleAgain();
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && !isFirstVisible) {
            visibleAgain();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isFirstVisible) {
            isFirstVisible = false;
        } else {
            if (getUserVisibleHint() && !isHidden()) {
                visibleAgain();
            }
        }
    }

    @Override
    public void onDestroyView() {
        if (mVDBinding != null) {
            mVDBinding.unbind();
        }
        getLifecycle().removeObserver(mViewModel);
        super.onDestroyView();
    }

    protected abstract int getViewModelId();//获取ViewModel的BR ID

    protected abstract int getContentLayout();//获取内容布局

    //初始化Intent里的数据
    protected void initBundleData() {
    }

    protected abstract void initView();//初始化界面控件

    protected void initObservers() {
        mViewModel.getBaseMld().observe(this, new Observer<BaseMldEvent>() {
            @Override
            public void onChanged(BaseMldEvent baseMldEvent) {
                switch (baseMldEvent.action) {
                    case SHOW_LOADING:
                        mActivity.showLoading(baseMldEvent.stringMsg);
                        break;
                    case HIDE_LOADING:
                        mActivity.hideLoading(baseMldEvent.stringMsg);
                        break;
                    case FINISH:
                        mActivity.finish();
                    case FINISH_WITH_RESULT:
                        getActivity().setResult(baseMldEvent.intMsg);
                        mActivity.finish();
                        break;
                }
            }
        });
    }

    protected void initData() {
    }

    /**
     * 碎片的非第一次可见
     */
    protected void visibleAgain() {
    }

    private Class getViewModelClass() {
        Class modelClass;
        Type type = getClass().getGenericSuperclass();
        if (type instanceof ParameterizedType) {
            modelClass = (Class) ((ParameterizedType) type).getActualTypeArguments()[1];
        } else {
            //如果没有指定泛型参数，则默认使用BasemViewModel
            modelClass = BaseViewModel.class;
        }
        return modelClass;
    }
}
